import {Injectable} from '@angular/core';
import {Http,Headers,RequestOptions} from '@angular/http';
import { PageInfo } from '../model/Page';
import { User } from '../model/User';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class UserService {
   
constructor(private _http: Http) {}

 private url: string = "http://192.168.1.129:8080/users/";

   //获取所有的用户
   getAllUser(): Promise<PageInfo> {
    return this._http.get(this.url)
               .toPromise()
               .then(response => response.json() as PageInfo)
               .catch(this.handleError);
  }

  //添加用户--修改用户
    addUser(user: User) {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        let body = JSON.stringify(user);
        return this._http.post(this.url, body,options)
                        .toPromise()
                        .then(response => response)
                        .catch(this.handleError);
    }

    //删除用户
     deleteUser(id:number){
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this._http.delete(this.url+id)
                        .toPromise()
                        .then(response => response)
                        .catch(this.handleError);
     }

    //根据id获取用户信息
     getUserById(id:number):Promise<User>{

       return this._http.get(this.url+id)
               .toPromise()
               .then(response => response.json())
               .catch(this.handleError);
     }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes onl
    return Promise.reject(error.message || error);
  }
}